import TableRender from '@/render/TableRender'
import { Component, Emit, Prop, Watch } from 'vue-facing-decorator'
import toNative from '@/utils/toNative'
import CDrawer from '@/components/drawer/Index'
import renderModal, {
    getModelValue,
    initModelValue,
    renderForm,
    type FormModalDto
} from '@/components/modal/Modal'
import { GenderCnEnum, getKeyToEnum, JoinCnEnum, SexCnEnum, VisibleCnEnum } from '@/const/enum'
import type { AddStaffReqDto, EditStaffReqDto, StaffDto } from '@/api/system/types'
import { addStaff, editStaff, getRoleList, getStaffInfo } from '@/api/system'
import { getSaleList } from '@/api/sale'
import { getProductBySale } from '@/api/deal'
import type { ProductDto } from '@/api/deal/types'
import DialogAllocateClient from './DialogAllocateClient'
import dayjs from 'dayjs'
import { Button } from 'ant-design-vue'
@Component
export class DrawerAddMember extends TableRender {
    @Prop() show!: boolean
    @Prop() userId?: null | number

    showDrawer = false
    title = '新建员工'
    staffData = {} as StaffDto
    productList = [] as ProductDto[]

    showAllocate = false

    @Emit('update:show')
    updateShow(val: boolean) {
        return val
    }

    @Emit('refresh')
    handleRefresh() {}

    @Watch('show', { immediate: true })
    async handleWatchShow() {
        this.showDrawer = this.show
        if (this.showDrawer) {
            this.basicForm = renderForm(this.basicFormConfig)

            if (!this.userId) return

            this.title = '修改组员信息'
            this.basicFormConfig.items.nickName.readonly = true
            this.basicFormConfig.items.idCardNo.hidden = true
            this.basicFormConfig.items.phonenumber.readonly = true
            this.staffData = await this.getUserInfo()
            this.productList = await this.getProductList()

            this.staffData.receiverSales =  this.staffData.receiverSales?.length && JSON.parse(this.staffData.receiverSales)

            console.log(1234, this.staffData)

            initModelValue(this.basicFormConfig, this.staffData)
            // 是否展示交接人员
            this.initShowReceiverSalesAndOptions()
          
            this.basicForm.clear()
        }
    }

    @Watch('showDrawer', { immediate: true })
    handleWatchShowDialog() {
        this.updateShow(this.showDrawer)
    }

    // 是否是编辑
    get isEdit() {
        return !!this.userId
    }

    // 销售且是离职状态
    get isSaleAndLeave() {
        const data = getModelValue(this.basicFormConfig)
        return data.crmAuditStatus === 2 && data.postIds === 1
    }

    // 非销售且是离职状态
    get isOtherAndLeave() {
        const data = getModelValue(this.basicFormConfig)
        return data.crmAuditStatus === 2 && data.postIds !== 1
    }

    basicFormConfig = this.initFormConfig() as FormModalDto
    initFormConfig() {
        return {
            title: '',
            width: '400px',
            theme: 'light',
            show: false,
            labelCol: {
                style: {
                    width: '9em'
                }
            },
            items: {
                nickName: {
                    name: '名称',
                    element: 'input',
                    required: true
                },
                idCardNo: {
                    name: '身份证号',
                    element: 'input',
                    required: true
                },
                phonenumber: {
                    name: '手机号',
                    element: 'input',
                    required: true
                },
                sex: {
                    name: '性别',
                    element: 'radioGroup',
                    options: getKeyToEnum(GenderCnEnum),
                    required: true
                },
                entryTime: {
                    name: '入职日期',
                    element: 'datetime',
                    type: 'date',
                    params: {
                        valueformat: 'YYYY-MM-DD',
                        format: 'YYYY-MM-DD'
                    },
                    required: true
                },
                deptId: {
                    name: '选择分组信息',
                    element: 'cascader',
                    optionsType: 'department',
                    props: {
                        emitPath: false
                    },
                    required: true
                },
                postIds: {
                    name: '组员类型',
                    element: 'select',
                    optionsType: 'memberType',
                    required: true,
                    callback: {
                        change: (val: number) => {
                            this.initShowReceiverSalesAndOptions()
                        }
                    }
                },
                role: {
                    name: '选择角色信息',
                    element: 'select',
                    // optionsType:'role',
                    params: {
                        valueKey: 'roleKey'
                    },
                    callback: {
                        method: async () => {
                            return (
                                await getRoleList({
                                    pageNum: 1,
                                    pageSize: 999
                                })
                            ).rows.map((i) => {
                                return {
                                    label: i.roleName,
                                    value: i
                                }
                            })
                        }
                    },
                    required: true
                },
                isJoinRankingList: {
                    name: '是否参加排行榜',
                    element: 'radioGroup',
                    options: getKeyToEnum(JoinCnEnum),
                    required: true
                },
                isShowRankingList: {
                    name: '排行榜是否可见',
                    element: 'radioGroup',
                    options: getKeyToEnum(VisibleCnEnum),
                    required: true
                },
                crmAuditStatus: {
                    name: '是否在职',
                    element: 'switch',
                    params: {
                        activeValue: 1,
                        inactiveValue: 2
                    },
                    callback: {
                        change: (val: number) => {
                            this.basicFormConfig.items.receiverSales.hidden = val === 1
                        }
                    }
                },
                receiverSales: {
                    name: '离职交接人员',
                    element: 'select',
                    required: true,
                    params: {
                        valueKey: 'saleId'
                    },
                    callback: {
                        focus: async () => {
     
                        }
                    }
                }
            },
            complete: async () => {
                const data = getModelValue(this.basicFormConfig)
                // await updatePayManagerUser(data)
                this.basicFormConfig.show = false
            },
            cancel: () => {
                this.basicFormConfig.show = false
            },
            init: () => {}
        } as FormModalDto
    }
    basicForm = {
        validate: async () => {},
        clear: () => {},
        element: () => <> </>
    }

    // 在职或不为商务时，隐藏交接人员
    async initShowReceiverSalesAndOptions() {
        const data = getModelValue(this.basicFormConfig)
        this.basicFormConfig.items.receiverSales.hidden =
            data.crmAuditStatus === 1 || data.postIds === 1
        // 展示交接人员时获取人员options
        !this.basicFormConfig.items.receiverSales.hidden && !this.basicFormConfig.items.receiverSales.options?.length && await this.initSalesOptions()
    }

    async initSalesOptions() {
        const res = await getSaleList()
        this.basicFormConfig.items.receiverSales.options = res
            .filter((i) => {
                return this.staffData.userId !== i.userId
            })
            .map((i) => {
                return {
                    label: i.saleName,
                    value: i
                }
            })
    }

    async getUserInfo() {
        const res = await getStaffInfo({
            userId: this.userId as number
        })
        res.entryTime = dayjs(res.entryTime).format('YYYY-MM-DD HH:mm:ss')
        res.postIds = res.postId
        res.role = res.roles[0]
        res.crmAuditStatus = res.status === '0' ? 1 : 2
        return res
    }

    async getProductList() {
        const res = await getProductBySale({
            saleId: this.staffData.saasUserId
        })
        return res
    }

    onShowAllocate() {
        this.showAllocate = true
    }

    async onConfirm() {
        this.basicForm.validate()
        const data = getModelValue(this.basicFormConfig)

        let params = {} as AddStaffReqDto
        params = {
            ...data
        }
        params.avatar = this.staffData?.avatar ?? ''
        params.crmAuditStatus = data.crmAuditStatus ?? 1
        params.userName = data.phonenumber
        params.entryTime = new Date(data.entryTime).getTime()
        params.roleIds = [data.role.roleId]
        params.roleKey = data.role.roleKey
        params.postIds = Array.isArray(data.postIds) ? data.postIds : [data.postIds]
        params.salesName = data.nickname
        delete (params as typeof data).role
        if (!this.isEdit) {
            params.password = 'lthd@2021.03'
            await addStaff(params)
        } else {
            const editParams = {
                ...params
            } as EditStaffReqDto
            delete (editParams as Partial<AddStaffReqDto>).idCardNo
            delete (editParams as Partial<AddStaffReqDto>).salesName
            const receiverSales = {} as {
                saleId: number
                saleName: string
            }
            if (editParams.crmAuditStatus === 2 && editParams.postIds?.[0] !== 1) {
                receiverSales.saleId = data.receiverSales.saleId
                receiverSales.saleName = data.receiverSales.saleName
            }
            editParams.receiverSales = JSON.stringify(receiverSales)
            editParams.userId = this.staffData.userId
            editParams.auditStatus = data.crmAuditStatus
            await editStaff(editParams)
        }
        this.showDrawer = false
        this.updateShow(this.showDrawer)
        this.handleRefresh()
    }

    render() {
        return (
            <>
                <CDrawer
                    v-model:show={this.showDrawer}
                    size={500}
                    title={this.title}
                    resetStyle={true}
                    showClose
                    v-slots={{
                        default: () => {
                            return (
                                <>
                                    {this.basicForm.element()}
                                    {this.isSaleAndLeave && (
                                        <div class="ml-20px">
                                            <div>
                                                待分配的客户<span class="text-blue-default">{this.productList?.length ?? 0}</span>
                                                位
                                            </div>
                                            <Button type="link" onClick={this.onShowAllocate}>
                                                批量分配
                                            </Button>
                                        </div>
                                    )}
                                </>
                            )
                        },
                        footer: () => {
                            return (
                                <Button type="primary" onClick={this.onConfirm}>
                                        确定
                                </Button>
                            )
                        }
                    }}
                ></CDrawer>
                <DialogAllocateClient v-model:show={this.showAllocate} saasUserId={this.staffData.saasUserId} productList={this.productList} onRefresh={this.getProductList}/>
            </>
        )
    }
}

export default toNative<{ userId: null | number }, { refresh: () => void }>(DrawerAddMember)
